package fti.uksw.ruang.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import fti.uksw.ruang.R;
import fti.uksw.ruang.model.CalendarEvent;

public class DayViewFragment extends Fragment {

	public static String TAG = DayViewFragment.class.getName();

	private static int HOURS = 24;
	private static int ROWS = HOURS * 2;
	private static int TOP_MARGINS = 30;
	private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
			30, 31 };
	private int daysInMonth;
	private int day, month, year;

	private RelativeLayout llBody;
	private ImageView ivNext;
	private ImageView ivPrev;
	private TextView tvCurrentDay;
	private ViewFlipper vf;

	private ArrayList<CalendarEvent> listEvent;
	private Map<String, ArrayList<CalendarEvent>> mapEvent;

	private OnDayViewListener mCallBack;

	public interface OnDayViewListener {
		public void onDayViewEventClick(ArrayList<CalendarEvent> mListKeg);
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mCallBack = (OnDayViewListener) activity;
		} catch (ClassCastException cce) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnDayViewListener");
		}
	}

	public void onDetach() {
		super.onDetach();
		mCallBack = null;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		listEvent = getActivity().getIntent().getParcelableArrayListExtra(
				CalendarEvent.TAG);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.caldayview, container, false);

		vf = (ViewFlipper) v.findViewById(R.id.vf_weekview);
		llBody = (RelativeLayout) v.findViewById(R.id.ll_weekview_body);
		ivNext = (ImageView) v.findViewById(R.id.iv_weekview_next);
		ivPrev = (ImageView) v.findViewById(R.id.iv_weekview_prev);
		tvCurrentDay = (TextView) v.findViewById(R.id.tv_weekview_currentday);

		// llBody.setOnTouchListener(vfListener);
		// llBody.setClickable(true);

		ivNext.setOnClickListener(ivClickListener);
		ivPrev.setOnClickListener(ivClickListener);
		ivNext.setClickable(true);
		ivPrev.setClickable(true);

		Calendar c = Calendar.getInstance();
		createTitleDay(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
				c.get(Calendar.YEAR));
		createBackground();
		// addEventToCal();
		return v;
	}

	private OnClickListener ivClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			if (v == ivNext) {
				if (daysInMonth > daysOfMonth[month]) {
					day = 1;

					if (month >= 11) {
						month = 0;
						year++;
					} else {
						month++;
					}
				} else {
					day++;
				}
				vf.setInAnimation(v.getContext(), R.anim.in_from_right);
				vf.setOutAnimation(v.getContext(), R.anim.out_to_left);
			} else if (v == ivPrev) {
				if (daysInMonth < 1) {
					if (month <= 0) {
						month = 11;
						year--;
					} else {
						month--;
					}
					day = daysOfMonth[month];
				} else {
					day--;
				}
				vf.setInAnimation(v.getContext(), R.anim.in_from_left);
				vf.setOutAnimation(v.getContext(), R.anim.out_to_right);
			}
			createTitleDay(day, month, year);
			createBackground();
			addEventToCal();
			vf.setDisplayedChild(1);
		}
	};

	private void createBackground() {

		llBody.removeAllViews();

		// create row background
		for (int i = 0; i < ROWS; i++) {
			RelativeLayout.LayoutParams rlParams = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.MATCH_PARENT, 1);
			rlParams.setMargins(
					(int) getResources().getDimension(
							R.dimen.calviewday_margin_left), TOP_MARGINS * i,
					0, 0);

			View v = new View(getActivity().getApplicationContext());
			v.setLayoutParams(rlParams);
			v.setBackgroundColor(Color.GRAY);

			llBody.addView(v);

			if (i % 2 == 1) {

				RelativeLayout.LayoutParams rlParams2 = new RelativeLayout.LayoutParams(
						RelativeLayout.LayoutParams.WRAP_CONTENT,
						RelativeLayout.LayoutParams.WRAP_CONTENT);
				rlParams2.setMargins(
						0,
						(TOP_MARGINS * i) - 15,
						0,
						(int) getResources().getDimension(
								R.dimen.calviewday_margin_right));
				TextView tv = new TextView(getActivity()
						.getApplicationContext());
				tv.setLayoutParams(rlParams2);
				tv.setTextSize(getResources().getDimension(
						R.dimen.textsize_calviewday_desc));
				tv.setTextColor(Color.BLACK);
				tv.setText(String.valueOf((i / 2) + 1));
				llBody.addView(tv);
			}
		}

	}

	private void createTitleDay(int _day, int _month, int _year) {
		SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy",
				Locale.getDefault());
		Calendar c = Calendar.getInstance();
		day = _day;
		month = _month;
		daysInMonth = daysOfMonth[_month];
		year = _year;
		c.set(_year, _month, _day);

		tvCurrentDay.setText(sdf.format(c.getTime()));
	}

	private void addEventToCal() {
		// example to add a event in weekview
		// 1dp = 1 minutes

		int marginMeasure = 1;
		int marginLeft = 0;
		int marginTop = 0;
		int marginRight = 0;
		int marginBottom = 0;
		// Log.d(TAG, "size : " + listEvent.size());
		mapEvent = new HashMap<String, ArrayList<CalendarEvent>>();
		for (CalendarEvent _ce : listEvent) {

			Calendar calendarStart = Calendar.getInstance();
			calendarStart.setTime(_ce.getStartTime());
			Calendar calendarStop = Calendar.getInstance();
			calendarStop.setTime(_ce.getEndTime());

			if ((calendarStart.get(Calendar.MONTH) == month && calendarStart
					.get(Calendar.YEAR) == year)
					|| (calendarStop.get(Calendar.MONTH) >= month && calendarStop
							.get(Calendar.YEAR) >= year)
					|| (calendarStop.get(Calendar.YEAR) > year)) {

				// calculate the diff between date
				Calendar tempCal = (Calendar) calendarStart.clone();
				long daysBetWeen = 0;
				while (tempCal.before(calendarStop)) {
					tempCal.add(Calendar.DAY_OF_MONTH, 1);
					daysBetWeen++;
				}

				for (int i = 0; i < daysBetWeen; i++) {

					if ((calendarStart.get(Calendar.DAY_OF_MONTH) == day)
							&& (calendarStart.get(Calendar.MONTH) == month)
							&& (calendarStart.get(Calendar.YEAR) == year)) {

						// minus 30 to make it in line with an hour
						marginTop = (calendarStart.get(Calendar.HOUR_OF_DAY) * 60 * marginMeasure)
								+ (calendarStart.get(Calendar.MINUTE) * marginMeasure)
								- 30;
						marginBottom = (calendarStop.get(Calendar.HOUR_OF_DAY) - calendarStart
								.get(Calendar.HOUR_OF_DAY))
								* 60
								* marginMeasure
								+ (calendarStop.get(Calendar.MINUTE) - calendarStart
										.get(Calendar.MINUTE)) * marginMeasure;

						RelativeLayout.LayoutParams rlParams2 = new RelativeLayout.LayoutParams(
								RelativeLayout.LayoutParams.MATCH_PARENT, 60);
						rlParams2
								.setMargins(
										(int) getResources()
												.getDimension(
														R.dimen.calviewday_text_desc_margin_left),
										marginTop,
										(int) getResources()
												.getDimension(
														R.dimen.calviewday_text_desc_margin_right),
										0);
						rlParams2.height = marginBottom;
						TextView tv = new TextView(getActivity()
								.getApplicationContext());
						tv.setLayoutParams(rlParams2);

						tv.setText(_ce.getSubject() + " "
								+ calendarStart.get(Calendar.HOUR_OF_DAY) + ":"
								+ calendarStart.get(Calendar.MINUTE) + "-"
								+ calendarStop.get(Calendar.HOUR_OF_DAY) + ":"
								+ calendarStop.get(Calendar.MINUTE) + "\n"
								+ _ce.getGuest().getDosen().getNama() + "\n"
								+ _ce.getPengguna().getNama() + "/"
								+ _ce.getPengguna().getNoTelp());
						tv.setTextColor(Color.BLACK);
						tv.setGravity(Gravity.CENTER);
						tv.setBackgroundResource(R.drawable.bg_trans);

						String tagTextView = _ce.getId() + _ce.getSubject();
						tv.setTag(tagTextView);
						tv.setOnClickListener(onClickEvent);
						
						ArrayList<CalendarEvent> _listEventForMap = mapEvent
								.get(tagTextView);
						if (mapEvent.containsKey(tagTextView)) {
							_listEventForMap = mapEvent.get(tagTextView);
						} else {
							_listEventForMap = new ArrayList<CalendarEvent>();
						}
						_listEventForMap.add(_ce);
						mapEvent.put(tagTextView, _listEventForMap);

						llBody.addView(tv);
						break;
					}
					calendarStart.add(Calendar.DAY_OF_MONTH, 1);
				}
			}
		}
	}

	private OnClickListener onClickEvent = new OnClickListener() {

		@Override
		public void onClick(View v) {
			mCallBack.onDayViewEventClick(mapEvent.get(v.getTag()));
		}
	};

	public void setListKegiatan(ArrayList<CalendarEvent> mListEvent) {
		createBackground();
		listEvent = mListEvent;
		addEventToCal();
	}

}
